#!/usr/bin/env python
# -*- coding: utf-8 -*
 
u"""Program name - short description
 
Example usage
=============
 
.. sourcecode:: bash
 
    python program_name.py -vvvvv action
 
:author: `Name Surname <mailto:foo@example.com>`__
"""

import os, sys, logging, optparse
import os

from MyClasses.MyMailer import MyMailer
from MyClasses.IDate import IDate
from MyClasses.MyConfigParser import MyConfigParser
from  ConfigParser import RawConfigParser

#: Glogbal logger instance
LOG = logging.getLogger(__name__)
#: Debug level names as a string
LOG_HELP = ','.join(["%d=%s" % (4-x, logging.getLevelName((x+1)*10)) for x in xrange(5)])
#: Console LOG format
LOG_FORMAT_CONS = '%(asctime)s %(name)-12s %(levelname)8st%(message)s'
#: File LOG format
LOG_FORMAT_FILE = '%(asctime)s %(name)s[%(process)d] %(levelname)10s %(message)s'
#: Levels of logging translation (count of -v, log level)
LOGLEVEL_DICT = { 1 : 50, 2:40, 3:20, 4:10, 5:1 }
 
DEFAULT_VERBOSITY = 0

CONF_FILE = 'configs/mail.ini'

def fetch_all_mailers():
    conf_parser = RawConfigParser()
    conf_parser.read( CONF_FILE )

    return [ MyMailer( MyConfigParser( conf_parser, sect) ) for sect in conf_parser.sections() ]
 
def run_mailers( needle, date, debug = 0 ):             
    
    providers = fetch_all_mailers()
    for mailer in providers:
        try:
            mailer.connect(debug)
            mailer.login()
            search_result = mailer.search( needle, date )
            mailer.output( search_result )
        except Exception, e:
            LOG.info('Failed with Exception %s', e)

def main():
    """ Main function - parses args and runs action """
    parser = optparse.OptionParser(usage="%prog or type %prog -h (--help) for help", description=__doc__, version="%prog",option_class=IDate )
    parser.add_option("-v", action="count", dest="verbosity", default = DEFAULT_VERBOSITY, help = "Verbosity. Add more -v to be more verbose (%s) [default: %%default]" % LOG_HELP)
    parser.add_option("-l", "--logfile", dest="logfile",    default = None, help = "Log to file instead off console [default: %default]" )
    parser.add_option("-d", "--date", dest="date",    default = None, help = "Mail message date [Example: 21-Dec-2012]" )
    parser.add_option("-s", "--subject", dest="subject",    default = None, help = "Mail message subject" )
 
    (options, args) = parser.parse_args()

    if not options.date:
        parser.error('Date should be given')

    if not options.subject:
        parser.error('Subject should be given')
 
    verbosity = LOGLEVEL_DICT.get(int(options.verbosity), DEFAULT_VERBOSITY)
 
    # Set up logging
    if options.logfile is None:
        logging.basicConfig(level=verbosity, format=LOG_FORMAT_CONS)
    else:
        logfilename = os.path.normpath(options.logfile)
        logging.basicConfig(level=verbosity, format=LOG_FORMAT_FILE, filename=logfilename, filemode='a')
        print >> sys.stderr, "Logging to %s" % logfilename
 
    # Run actions
    LOG.info("Starting %s, from %s using verbosity %s/%s as PID %d", __name__, os.path.abspath(__file__), options.verbosity, verbosity, os.getpid())
 
    run_mailers(options.subject, options.date, int(options.verbosity))
 
    LOG.info("Exited %s, from %s using verbosity %s/%s  as PID %d", __name__, os.path.abspath(__file__), options.verbosity, verbosity, os.getpid())
 
if __name__ == "__main__":
    main()